iT邦幫忙

0

Day 12: 387. First Unique Character in a String

  • 分享至 

  • xImage
  •  

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:
Input: s = "leetcode"
Output: 0
Explanation:
The character 'l' at index 0 is the first character that does not occur at any other index.
Example 2:
Input: s = "loveleetcode"
Output: 2
Example 3:
Input: s = "aabb"
Output: -1
解題思路
1.找出字串中第一個只出現一次的字元,並回傳其索引。
若不存在,回傳-1。
2.思路:
第一次遍歷:用count[26]統計每個字母出現次數。
第二次遍歷:找到第一個count == 1的字元,回傳其索引。
3.為什麼這樣做?
因為題目只包含小寫字母(a到z),
用陣列統計比HashMap更快。
https://ithelp.ithome.com.tw/upload/images/20251014/20179424TCwmqduEyn.png


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言